package gui.view;

import java.awt.Component;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JEditorPane;
import javax.swing.JScrollPane;

import gui.parser.Attr;

public class EditText extends TextView {
	private JEditorPane view;
	private JScrollPane layout;
	private boolean editable;
	private OnTextChangedListener onTextChangedListener;

	public EditText(Attr attr) {
		super(attr);
	}

	@Override
	protected void addAllListener() {
		super.addAllListener();
		view.addKeyListener(new KeyListener() {

			@Override
			public void keyTyped(KeyEvent e) {

			}

			@Override
			public void keyReleased(KeyEvent e) {
				if (onTextChangedListener != null) {
					onTextChangedListener.afterTextChanged(EditText.this);
					try {
						onTextChangedListener.onTextChanged(view.getText(), 0, 0, view.getText().length());
					} catch (Exception e2) {
					}
				}
			}

			@Override
			public void keyPressed(KeyEvent e) {
				if (onTextChangedListener != null) {
					onTextChangedListener.beforeTextChanged(view.getText(), 0, 0, 0);
				}
			}
		});
	}

	@Override
	public String getText() {
		return view.getText();
	}

	@Override
	public void init() {
		super.init();
		editable = getBooleanAttr("gui:editable", true);
		setEnable(true);
		setEditable(isEditable());
		view = new JEditorPane();
		layout = new JScrollPane(view);
	}

	@Override
	public void invalidate() {
		super.invalidate();
		view.setText(text);
		view.setEditable(isEditable());
		view.setEnabled(isEnable());
		if (font != null)
			view.setFont(font);
	}

	@Override
	public Component getView() {
		return layout;
	}

	protected JEditorPane getEdit() {
		return view;
	}

	public boolean isEditable() {
		return editable;
	}

	public void setEditable(boolean editable) {
		this.editable = editable;
		if (editable)
			setEnable(editable);
	}

	public void setOnTextChangedListener(OnTextChangedListener onTextChangedListener) {
		this.onTextChangedListener = onTextChangedListener;
	}

	public static interface OnTextChangedListener {
		/**
		 * 
		 * @param s
		 *            当前字符串
		 * @param start
		 * @param before
		 *            之前文本长度
		 * @param count
		 *            当前文本长度
		 */
		void onTextChanged(CharSequence s, int start, int before, int count);

		/**
		 * 
		 * @param s
		 *            修改之前的文本
		 * @param start
		 * @param count
		 *            之前文本长度
		 * @param after
		 *            修改后文本长度
		 */
		void beforeTextChanged(CharSequence s, int start, int count, int after);

		/**
		 * 提供后续的修改
		 * 
		 * @param s
		 */
		void afterTextChanged(EditText s);
	}
}
